<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar v-if="!getQuery.sharedId">
        <a-button
          type="default"
          @click="handleTagsForm({ ids: getSelectRowKeys().join(',') })"
          v-auth="'filemanager:filemanager:view'"
        >
          <Icon icon="i-ant-design:tags-outlined" /> {{ t('标签') }}
        </a-button>
        <ListSelect
          ref="listSelectRef"
          :configFile="import('../filemanagerTag/select')"
          :checkbox="false"
          @select="listSelectOnSelect"
          v-show="false"
        />
      </template>
      <template #firstColumn="{ record }">
        <div v-if="record.fileType == 'folder'">
          <Icon icon="i-fa:folder-o" /> &nbsp;
          <a
            @click="
              handleGoFolder({
                id: record.folderId,
                sharedId: record.sharedId,
                groupType: record.groupType,
              })
            "
          >
            {{ record.fileName }}
          </a>
          <FileManagerTags :record="record" @click="handleTagClick" />
        </div>
        <div v-else>
          <Icon icon="i-fa:file-text-o" /> &nbsp;
          <a @click="handlePreview({ id: record.fileUploadId })">
            {{ record.fileName }}
          </a>
          <FileManagerTags :record="record" @click="handleTagClick" />
        </div>
      </template>
    </BasicTable>
    <TagsForm @register="registerTagsModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup name="ViewsFilemanagerList">
  import { ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { filemanagerListData } from '/@/api/filemanager/filemanagerMyFile';
  import { useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import TagsForm from '../filemanagerTag/assign.vue';
  import { useGo, useQuery } from '/@/hooks/web/usePage';
  import { openWindowLayer } from '/@/utils';
  import FileManagerTags from '../components/FileManagerTags.vue';
  import { ListSelect } from '/@/components/ListSelect';
  import { filemanagerSharedView } from '/@/api/filemanager/filemanagerShared';
  import qs from 'qs';

  const { t } = useI18n('filemanager');
  const { ctxAdminPath, filePreview } = useGlobSetting();
  const { meta } = unref(router.currentRoute);
  const getTitle = {
    icon: meta.icon || 'i-simple-line-icons:docs',
    value: meta.title || t('文件管理'),
  };
  const getQuery = useQuery();
  const folderId = ref<string>(getQuery.value.folderId);
  const sharedId = ref<string>(getQuery.value.sharedId);
  const tagIdRef = ref<string>('');
  const go = useGo();

  const searchForm: FormProps = {
    baseColProps: { md: 8, lg: 6 },
    labelWidth: 90,
    schemas: [
      {
        label: t('文件名称'),
        field: 'fileName',
        component: 'Input',
      },
      {
        label: t('上传者'),
        field: 'createBy',
        fieldLabel: 'createByName',
        component: 'ListSelect',
        componentProps: {
          selectType: 'empUserSelect',
        },
      },
      {
        label: t('上传时间'),
        field: 'dateRange',
        component: 'RangePicker',
        componentProps: {},
      },
    ],
    fieldMapToTime: [['dateRange', ['createDate_gte', 'createDate_lte']]],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('名称'),
      dataIndex: 'fileName',
      key: 'a.file_name',
      sorter: true,
      width: 300,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('文件类型'),
      dataIndex: 'fileType',
      key: 'a.file_type',
      format: (text: string) => {
        return { image: t('图片'), media: t('媒体'), file: t('文档') }[text] ?? '';
      },
      sorter: true,
      width: 90,
      align: 'center',
    },
    {
      title: t('文件大小'),
      dataIndex: 'fileSizeFormat',
      sorter: false,
      width: 130,
      align: 'center',
    },
    {
      title: t('上传者'),
      dataIndex: 'createByName',
      key: 'a.create_by',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('上传时间'),
      dataIndex: 'createDate',
      key: 'a.create_date',
      sorter: true,
      width: 130,
      align: 'center',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        icon: 'i-ant-design:download-outlined',
        title: t('下载文件'),
        onClick: handleDownload.bind(this, { id: record.fileUploadId }),
        auth: 'filemanager:filemanager:edit',
        ifShow: () => record.fileType !== 'folder',
      },
    ],
  };

  const [registerTagsModal, tagsAction] = useModal();
  const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys }] = useTable({
    api: filemanagerListData,
    beforeFetch: (params) => {
      params.folderId = folderId.value;
      params.sharedId = sharedId.value;
      // params.groupType = groupTypeRef.value;
      params.tagId = tagIdRef.value;
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    clickToRowSelect: false,
    rowSelection: {
      type: 'checkbox',
    },
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
  });

  const listSelectRef = ref<any>(null);

  function handleTagsForm(record: Recordable) {
    if (!record.ids || record.ids == '') {
      listSelectRef.value.openSelectModal();
      return;
    }
    tagsAction.openModal(true, record);
  }

  function listSelectOnSelect(values: Recordable[]) {
    if (values && values.length > 0) {
      handleTagClick(values[0]);
    }
  }

  async function handleTagClick(tag: Recordable) {
    tagIdRef.value = tag.tagId;
    await handleSuccess();
    tagIdRef.value = '';
  }

  function handlePreview(record: Recordable) {
    openWindowLayer(
      ctxAdminPath + '/filemanager/download/' + record.id + '?preview=' + filePreview,
    );
  }

  async function handleDownload(record: Recordable) {
    downloadByUrl({ url: ctxAdminPath + '/filemanager/download/' + record.id });
  }

  async function handleGoFolder(record: Recordable) {
    if (record.sharedId && record.groupType != 'global') {
      const url = await filemanagerSharedView({ id: record.sharedId });
      const idx = url.indexOf('?');
      go({ path: url.substring(0, idx), query: qs.parse(url.substring(idx + 1)) });
    } else {
      go({ path: '/filemanager/list', query: { folderId: record.id } });
    }
  }

  async function handleSuccess() {
    await reload();
    setSelectedRowKeys([]);
  }
</script>
